package com.fare.taluo.core.domain.config.city.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.criterion.Order;
import org.springframework.stereotype.Repository;

import com.dayatang.hibernate.EntityRepositoryHibernate;
import com.fare.taluo.core.domain.config.city.CityEntity;
import com.fare.taluo.core.domain.config.city.CityEntityRepository;
import com.fare.taluo.util.StringUtils;
@Repository
public class CityEntityRepositoryImpl extends EntityRepositoryHibernate
implements CityEntityRepository{
	
	 public List<CityEntity> findCityEntityByCityCode(String citytyCode){
	    	List<Object> list = new ArrayList<Object>();
	    	list.add(citytyCode);
	    	List<CityEntity> cityEntity=super.find("from CityEntity c where c.code=?",list.toArray(),CityEntity.class);
	    	return cityEntity;
	    }

	@SuppressWarnings("unchecked")
	@Override
	public List<CityEntity> findAll() {
		return getSession().createCriteria(CityEntity.class)
				.addOrder(Order.asc("treeLevel")).addOrder(Order.asc("pid")).addOrder(Order.asc("id"))
				.setCacheable(true).list();
	}

	@Override
	public List<CityEntity> findCityByConditions(String name, String code ) {
		List<Object> params = new ArrayList<Object>();
		String hql = "from CityEntity c where 1=1" ;
		String names = null;
		try {
			names = URLDecoder.decode(name, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		if(StringUtils.isNotEmpty(names)){
			hql += " and c.name= ?";
			params.add(names);
		}
		if(StringUtils.isNotEmpty(code)){
			hql += " and c.code= ?";
			params.add(code);
		}
		
		List<CityEntity> list = super.find(hql,params.toArray(),CityEntity.class);
		return list;
	}

	@Override
	public List<CityEntity> findCityByIorChina(int flag) {
		List<Object> params = new ArrayList<Object>();
		String hql = "from CityEntity c where 1=1" ;
		hql += " and c.isInternational= ?";
		params.add(flag);
		
		List<CityEntity> list = super.find(hql,params.toArray(),CityEntity.class);
		return list;
	}
	
	@Override
	public void saveOrUpdate(CityEntity cityEntity) {
		super.save(cityEntity);
	}

	@Override
	public void delete(CityEntity cityEntity) {
		super.remove(cityEntity);
	}

	@Override
	public void saveInternationalImg(String areaName, String name) {
			String hql="update CityEntity t set t.code= ? ";
			List<Object> list = new ArrayList<Object>();
			list.add(areaName);
			String condition = " where t.name = ? ";
			list.add(name);
			hql=hql+condition;
			super.executeUpdate(hql,list.toArray() );
	}


}
